package com.chao.mail.core.impl

import com.chao.mail.core.Mail
import com.chao.mail.core.MailStatus
import com.chao.mail.core.interfaces.IMailSender
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.mail.MailException
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.stereotype.Component
import javax.mail.Message
import javax.mail.internet.MimeMessage

@Component
class SimpleMailSender: IMailSender {
    @Autowired
    lateinit var javaMailSender: JavaMailSender

    override fun sendMail(mail: Mail) {
        val memeMessage = convertMailToMine(mail)
        try {
            javaMailSender.send(memeMessage)
            mail.status = MailStatus.SENT
        }catch (e: MailException){
            mail.status = MailStatus.ERROR
        }
    }

    private fun convertMailToMine(mail: Mail): MimeMessage{
        val mineMessage: MimeMessage = javaMailSender.createMimeMessage()
        mineMessage.setFrom(mail.from)
        mineMessage.setRecipients(Message.RecipientType.TO, mail.to)
        mineMessage.subject = mail.subject
        mineMessage.setText(mail.text)
        return mineMessage
    }
}